package com.seal.yoyoshop.dao.impl;

import com.seal.yoyoshop.bin.User;
import com.seal.yoyoshop.dao.UserDao;
import com.seal.yoyoshop.util.DBUtils;

import java.util.List;
import java.util.Map;

public class UserDaoImpl implements UserDao {
    @Override
    public int insertUser(User user) {
        String sql = "INSERT INTO user VALUES(null , ? , ? , ? , ? , ? , 1)";
        int row = DBUtils.update(sql,user.getUsername(),user.getPassword(),user.getName(),user.getPhone(),user.getAddress());
        return row;
    }

    @Override
    public User selectUserByUsername(String username) {
        String sql = "SELECT * FROM user WHERE username = ?";
        User user = DBUtils.queryOne(sql,User.class,username);
        return user;
    }

    @Override
    public User selectUserByUsernameAndPassword(String username, String password) {
        String sql = "SELECT * FROM user WHERE username = ? AND password = ?";
        User user = DBUtils.queryOne(sql,User.class,username,password);
        return user;
    }

    @Override
    public int updatePassword(String username, String password) {
        String sql = "UPDATE user SET password = ? WHERE username = ?";
        int flag = DBUtils.update(sql,password,username);
        return flag;
    }
    @Override
    public boolean updateUser(User user) {
        String sql = "UPDATE user SET password = ?, name = ?, phone = ?, address = ?,status = ? WHERE username = ?";
        int flag = DBUtils.update(sql,user.getPassword(),user.getName(),user.getPhone(),user.getAddress(),user.getStatus(),user.getUsername());
        if (flag == 1)return true;
        return false;
    }

    @Override
    public List<User> selectUser(int page, int size) {
        String sql = "SELECT * FROM user WHERE status = 1 LIMIT ?, ?";
        List<User> userList = DBUtils.query(sql,User.class,(page-1)*size,size);
        return userList;
    }

    @Override
    public long selectUserCount() {
        String sql = "SELECT count(*) AS count FROM user WHERE status = 1";
        Map<String, Object> map = DBUtils.queryOne(sql);
        long count =(long)map.get("count");
        return count;
    }

    @Override
    public User selectUserById(int id) {
        String sql = "SELECT * FROM user WHERE id = ?";
        User user = DBUtils.queryOne(sql,User.class,id);
        return user;
    }
}